﻿#include <QPainter>
#include <QDebug>

#include "CPlcItemBranch.h"

CPlcItemBranch::CPlcItemBranch(const QRectF &rect,
                               const int8_t type,
                               const QString &str,
                               IPlcBaseItem *parent)
    : IPlcBaseItem(parent)
{
    mVariableNum  = str;
    mSelectActive = false;
    mSwitchOn     = false;
    mType         = type;
    setRect(rect);
}

CPlcItemBranch::~CPlcItemBranch()
{
    //如果当前为选中状态
    if (mSelectActive) setOnlySelectItem(NULL);
}

QRectF CPlcItemBranch::getRect()
{
    return mRect;
}

void CPlcItemBranch::setRect(const QRectF &rect)
{
    if (mRect == rect) return;
    //准备调整几何边界
    prepareGeometryChange();
    mRect         = rect;
    mBoundingRect = QRectF();
    // 缩放比例
    mdScale = mRect.width() / 100.0;
    //重绘
    update();
}

IPlcBaseItem *CPlcItemBranch::getBranch()
{
    return mBranch;
}

void CPlcItemBranch::setBranch(IPlcBaseItem *item)
{
    mBranch = item;
}

void CPlcItemBranch::deleteBranch()
{
    mBranch = NULL;
}

void CPlcItemBranch::setSelectActive(bool status)
{
    //复位之前选中的图元
    if (this != getOnlySelectItem())
    {
        if (getOnlySelectItem() != NULL)
            getOnlySelectItem()->setSelectActive(false);
    }

    if (mSelectActive == status) return;

    mSelectActive = status;
    status ? setOnlySelectItem(this) : setOnlySelectItem(NULL);
    //重绘图元
    update();
}

void CPlcItemBranch::setSwitchOn(bool value)
{
    if (mSwitchOn == value) return;

    mSwitchOn = value;
    //重绘图元
    update();
}

int8_t CPlcItemBranch::getItemType()
{
    return mType;
}

QRectF CPlcItemBranch::boundingRect() const
{
    if (mBoundingRect.isNull()) mBoundingRect = mRect;

    return mBoundingRect;
}

void CPlcItemBranch::paint(QPainter *painter,
                           const QStyleOptionGraphicsItem *option,
                           QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    // 设置反走样
    painter->setRenderHint(QPainter::Antialiasing, true);
    painter->setRenderHint(QPainter::TextAntialiasing, true);

    QBrush blackBrush(Qt::black);
    QBrush blueBrush(QColor(2, 167, 240));
    QPen pen;

    //设置画笔为实线
    pen.setStyle(Qt::SolidLine);
    pen.setWidth(0);   //线宽1
    //根据信号接通状态设置导线颜色
    if (mSwitchOn)
    {
        pen.setBrush(blueBrush);   //蓝色
    }
    else
    {
        pen.setBrush(blackBrush);   //黑色
    }
    painter->setPen(pen);
    double x1 = mRect.left() + mdScale * 50;
    double y1 = mRect.top();
    double y2 = mRect.bottom();
    painter->drawLine(x1, y1, x1, y2);   //画直线
}

bool CPlcItemBranch::getSelectActiveEnb()
{
    return false;
}

bool CPlcItemBranch::getSelectActive()
{
    return mSelectActive;
}
